package com.gitee.loyo.impl;

import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.streams.ReadStream;
import io.vertx.core.streams.impl.InboundBuffer;

public class BufferReadStream implements ReadStream<Buffer> {
    private final InboundBuffer<Buffer> queue;
    private Handler<Void> endHandler;

    public BufferReadStream(Context context) {
        queue = new InboundBuffer(context);
        queue.pause();
    }

    @Override
    public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
        queue.exceptionHandler(handler);
        return this;
    }

    @Override
    public ReadStream<Buffer> handler(Handler<Buffer> handler) {
        queue.handler(handler);
        queue.resume();
        return this;
    }

    @Override
    public ReadStream<Buffer> pause() {
        queue.pause();
        return this;
    }

    @Override
    public ReadStream<Buffer> resume() {
        queue.resume();
        return this;
    }

    @Override
    public ReadStream<Buffer> fetch(long amount) {
        queue.fetch(amount);
        return this;
    }

    @Override
    public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
        this.endHandler = endHandler;
        return this;
    }

    public void read(Buffer buffer) {
        queue.write(buffer);
    }

    public boolean tryEnd() {
        if(endHandler == null){
            return false;
        }
        endHandler.handle(null);
        return true;
    }
}
